const express = require('express');
const { handleError, executeQuery, formatDateTime } = require('../utils');
const router = express.Router();


function isValidPassword(password) {
    const passwordRegex = /^.{6,}$/; // 正则：6 位数字
    return passwordRegex.test(password);
}


// 查询用户列表信息和精准查询某个用户的信息
router.post('/list', async (req, res) => {
    const { page = 1, pageSize = 10, search = '', sex = '', role = '', user_id = '' } = req.body;
    const offset = (page - 1) * pageSize;
    const limit = pageSize;

    const searchQuery = `%${search}%`;

    if (user_id) {
        const query = `SELECT * FROM users WHERE user_id = ?`;
        try {
            const user = await executeQuery(query, [user_id]);

            if (user.length === 0) {
                return res.status(404).json({ message: '用户未找到' });
            }

            const formattedUser = {
                ...user[0],
                created_at: formatDateTime(user[0].created_at),
                updated_at: formatDateTime(user[0].updated_at),
            };

            return res.json({ data: formattedUser });
        } catch (error) {
            return handleError(error, res);
        }
    }

    const totalQuery = `
        SELECT COUNT(*) AS total
        FROM users
        WHERE (user_id LIKE ? OR name LIKE ?) 
          AND (? = '' OR sex = ?) 
          AND (? = '' OR role = ?);
    `;

    const query = `
        SELECT * FROM users
        WHERE (user_id LIKE ? OR name LIKE ?)
          AND (? = '' OR sex = ?)
          AND (? = '' OR role = ?)
        LIMIT ${limit} OFFSET ${offset};
    `;

    try {
        const totalResult = await executeQuery(totalQuery, [searchQuery, searchQuery, sex, sex, role, role]);
        const total = totalResult[0].total;
        const users = await executeQuery(query, [searchQuery, searchQuery, sex, sex, role, role]);

        users.forEach(user => {
            user.created_at = formatDateTime(user.created_at);
            user.updated_at = formatDateTime(user.updated_at);
        });

        res.json({ total, page, pageSize, data: users });
    } catch (error) {
        handleError(error, res);
    }
});

// 新增用户
router.post('/add', async (req, res) => {
    const { user_id, name, role, borrow_limit, phone, email, sex } = req.body;
    const password = '000000';

    const checkQuery = `SELECT user_id FROM users WHERE user_id = ?`;

    const query = `
        INSERT INTO users (user_id, name, password, role, borrow_limit, phone, email, sex, created_at, updated_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW());
    `;

    try {
        const existingUser = await executeQuery(checkQuery, [user_id]);

        if (existingUser.length > 0) {
            return res.status(400).json({ message: '用户ID已存在，请使用其他ID' });
        }

        await executeQuery(query, [user_id, name, password, role, borrow_limit, phone, email, sex]);
        res.json({ message: '用户添加成功' });
    } catch (error) {
        handleError(error, res);
    }
});

// 更新用户信息
router.post('/update', async (req, res) => {
    const { user_id, name, password, phone, email, sex, borrow_limit } = req.body;

    let updateFields = [];
    let values = [];

    if (name) {
        updateFields.push("name = ?");
        values.push(name);
    }

    if (password) {
        // 校验密码是否至少为 6 位
        if (isValidPassword(password)) {
            // 如果校验通过，准备更新字段
            updateFields.push("password = ?");
            values.push(password);
        } else {
            // 如果校验失败，返回错误响应
            return res.status(403).json({ message: '密码至少为6位' });
        }
    }

    if (phone) {
        updateFields.push("phone = ?");
        values.push(phone);
    }
    if (email) {
        updateFields.push("email = ?");
        values.push(email);
    }
    if (sex) {
        updateFields.push("sex = ?");
        values.push(sex);
    }
    if (borrow_limit) {
        updateFields.push("borrow_limit = ?");
        values.push(borrow_limit);
    }

    // 总是更新更新时间
    updateFields.push("updated_at = NOW()");
    values.push(user_id);

    if (updateFields.length > 0) {
        const query = `
            UPDATE users
            SET ${updateFields.join(', ')}
            WHERE user_id = ?;
        `;

        try {
            await executeQuery(query, values);
            res.json({ message: '用户信息更新成功' });
        } catch (error) {
            handleError(error, res);
        }
    } else {
        res.status(400).json({ message: '没有提供更新的字段' });
    }
});

// 删除用户
router.post('/delete', async (req, res) => {
    const { user_id } = req.body;
    const query = 'DELETE FROM users WHERE user_id = ?;';

    try {
        await executeQuery(query, [user_id]);
        res.json({ message: '用户删除成功' });
    } catch (error) {
        handleError(error, res);
    }
});

module.exports = router;
